<template>
  <a-popover placement="bottomLeft" title="分类" trigger="click" :overlayStyle="{ width: width + 'px' }">
    <template slot="content">
      <a-select
        v-model="selectValue"
        mode="tags"
        label-in-value
        style="width: 100%"
        @change="handleChange"
        placeholder="请输入文字搜索，Enter键入可添加自定义分类"
      />
      <div style="width: 100%; margin-top: 10px; padding: 5px;">
        <template v-for="tag in tags">
          <a-checkable-tag
            :key="tag.key"
            :checked="selectedTags.indexOf(tag) > -1"
            @change="checked => selectTagChange(tag, checked)"
            style=" font-size:15px; padding: 5px"
          >
            {{ tag.label }}
          </a-checkable-tag>
        </template>
      </div>
    </template>
    <template slot="title">
      <span>{{ title }}</span>
    </template>
    <a-button icon="plus" @click="pop">
      添加分类
    </a-button>
  </a-popover>
</template>

<script>
import { getAction, postAction } from '@/api/manage'

export default {
  name: 'JInputPop',
  props: {
    title: {
      type: String,
      default: '',
      required: false
    },
    height: {
      type: Number,
      default: 200,
      required: false
    },
    width: {
      type: Number,
      default: 150,
      required: false
    },
    value: {
      required: false
    },
    disabled: {
      type: Boolean,
      default: false
    }

  },
  data() {
    return {
      selectValue: [], // 输入值
      selectedTags: [],
      tags: [],
      url: {
        list: '/articleSort/genArticSortList',
        add: '/articleSort/addSort'
      }
    }
  },
  mounted() {
    this.initTags()
  },
  methods: {
    initTags() {
      getAction(this.url.list, {}).then((res) => {
        if (res.success) {
          this.tags = res.result
        }
      })
    },
    pop() {
      this.$emit('clean')
    },
    handleChange(value) {
      this.selectedTags = []
      let data = {
        'name': value[0].key
      }
      postAction(this.url.add, data).then((res) => {
        if (res.success) {
          this.$emit('change', res.result, true)
          this.selectValue = []
          this.initTags()
          this.selectedTags.push(res.result)
        } else {
          this.selectValue = []
          this.$message.error(res.message)
        }
      })
    },
    selectTagChange(tag, checked) {
      const { selectedTags } = this
      const nextSelectedTags = checked
        ? [...selectedTags, tag]
        : selectedTags.filter(t => t !== tag)
      if (nextSelectedTags.length <= 3) {
        this.selectedTags = nextSelectedTags
        this.$emit('change', tag, checked)
      } else {
        this.$message.error('每篇文章只能选择3个分类！')
      }
    }
  }
}
</script>

<style scoped>

</style>
